﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using Sinacor.Infra.UI.Session;
using Sinacor.Infra.UI.Authentication;
using Sinacor.Infra.Service.Data;
using System.Data.Common;
using System.Data;
using Sinacor.Infra.UI.Security.Licensing;
using Sinacor.Infra.UI.Controls.SmartClient;
using Sinacor.Infra.UI.Messaging;
using Sinacor.Infra.UI.Desktop.SmartClient;
using Sinacor.Infra.UI.Messaging.SmartClient;
using Sinacor.Infra.UI.Messaging.Internal;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using Sinacor.UI.Design.Tester.View.SmartClient;

namespace SinacorTester
{
    /// <summary>
    /// Interaction logic for AlternativeMenu.xaml
    /// </summary>
    public partial class AlternativeMenu : Window
    {
        string fileName = "SinacorTesterDllsConfiguration.txt";
        
        public AlternativeMenu()
        {
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AlternativeMenu_Loaded);
        }

        void AlternativeMenu_Loaded(object sender, RoutedEventArgs e)
        {
            LoadConfiguration();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="classe"></param>
        private void OpenWindow()
        {
            if (LstDll.SelectedIndex < 0)
            {
                SinacorMessageBox.Show("Selecione uma dll para exibir suas janelas.");
                return;
            }

            if (LstJanelas.SelectedIndex < 0)
            {
                SinacorMessageBox.Show("Selecione uma janela para exibir.");
                return;
            }

            string item = LstJanelas.SelectedItem.ToString();
            string[] elementosDll = item.ToString().Split('.');

            string assembly = LstDll.SelectedItem.ToString() ;   
            string classe = LstJanelas.SelectedItem.ToString();
            
            SessionManager _sessionaManager = SessionManager.GetInstance();

            Sinacor.Infra.UI.Authentication.Company company = new Sinacor.Infra.UI.Authentication.Company();
            company.Id = 15;
            company.Name = "";

            string tokenID = _sessionaManager.CreateSession(_sessionaManager.GetCurrentSession().User, company).TokenID;

             DesktopVirtual _virtualDesktop = DesktopVirtual.GetInstance();
            _virtualDesktop.ChangeDesktopVirtual(tokenID);

            WindowController wc = new WindowController();
            wc.OpenWindow(assembly, classe, new List<string>());

            SaveConfiguration();
        }
        
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenWindow();
        }

        private void BtnCaminho_Click(object sender, RoutedEventArgs e)
        {
            txtCaminho.Text = "";
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = false;
            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtCaminho.Text = fbd.SelectedPath;
                GetDllsInFolder();
            }


        }
        private void GetDllsInFolder()
        {
            string path = txtCaminho.Text.ToLower();

            if (path.Length > 0)
            {
                LstDll.Items.Clear();

                if (Directory.Exists(path))
                {
                    string[] files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);

                    foreach (string file in files)
                    {
                        FileInfo f = new FileInfo(file);

                        if (f.Name == "Sinacor.UI.Design.Tester.View.SmartClient.exe" || f.Name.Substring(f.Name.Length - 3).ToLower() == "dll")
                        {
                            LstDll.Items.Add(f.Name);
                        }
                    }
                }
                else
                    SinacorMessageBox.Show("O caminho selecionado não existe.");
            }
            else
                SinacorMessageBox.Show("Selecione um diretório para exibir as Dlls.");        
        }

        private void ClearData()
        {
        }

        private void txtCaminho_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                LstJanelas.Items.Clear();
                GetDllsInFolder();
            }
        }

        private void GetWindowsInDlls()
        {
            if (LstDll.SelectedIndex < 0)
                return;

            string item = LstDll.SelectedItem.ToString();
            string path = txtCaminho.Text + @"\" + item;

            if(!File.Exists(path))
            {
                SinacorMessageBox.Show("O arquivo " + path + " não existe." );
                return;
            }

            Assembly dll= Assembly.LoadFrom(path);

            LstJanelas.Items.Clear();

            foreach(Type t in dll.GetTypes())
            {
                if (t.BaseType == typeof(SinacorWindow))
                {
                    LstJanelas.Items.Add(t.FullName);
                }
            }

        }

        private void SaveConfiguration()
        {
            if (File.Exists(fileName))
                File.Delete(fileName);

            TextWriter tw = new StreamWriter(fileName);
            tw.WriteLine("PATH=" + txtCaminho.Text);
            
            if(LstDll.SelectedIndex >= 0)
                tw.WriteLine("DLL=" + LstDll.SelectedItem.ToString());
            else
                tw.WriteLine("DLL=");

            if (LstJanelas.SelectedIndex >= 0)
                tw.WriteLine("WINDOW=" + LstJanelas.SelectedValue.ToString());
            else
                tw.WriteLine("WINDOW=");
            
            tw.Close();
            tw = null;
        }

        private void LoadConfiguration()
        {
            if (File.Exists(fileName))
            {
                TextReader tw = new StreamReader(fileName);

                try
                {
                    txtCaminho.Text = tw.ReadLine().Replace("PATH=", "");
                    GetDllsInFolder();
                    LstDll.SelectedItem = tw.ReadLine().Replace("DLL=", "");
                    LstJanelas.SelectedItem = tw.ReadLine().Replace("WINDOW=", "");
                }
                catch { }
                finally
                {
                    tw.Close();
                    tw = null;
                }
            }
            else
            {
                txtCaminho.Text = System.Windows.Forms.Application.StartupPath;
                GetDllsInFolder();
                LstDll.SelectedItem = "Sinacor.UI.Design.Tester.View.SmartClient.exe";
                
            }
        }

        private void LstDll_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetWindowsInDlls();
        }
    }
}


